import { Sprite } from '../engine/nodes/sprite.js';
import { CanvasTexture } from '../engine/core/texture.js';
import { databus } from './databus.js'
import { vec3 } from '../engine/gl-matrix/index.js'

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

const atlas = document.createElement("img")
atlas.src = 'images/Common.png';

export class UI extends Sprite {
    constructor() {
        let canvas = document.createElement("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        let ctx = canvas.getContext("2d");
        ctx.textBaseline = "top";

        let texture = new CanvasTexture(canvas);

        super({ texture: texture });

        this.scale = vec3.fromValues(databus.rightX, 1.0, 1.0);
        this.translation = vec3.fromValues(0.0, 0.0, 0.5);

        this._canvas = canvas;
        this._ctx = ctx;
        this._texture = texture;
        this._score = -1;
    }

    onUpdate(timestamp, frameDelta) {
        if (databus.gameOver) {
            this._score = databus.score;

            this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
            this.renderGameScore(this._ctx, this._score);
            this.renderGameOver(this._ctx, this._score);
            this.updateTexture(this._texture);
        }
        else {
            if (this._score != databus.score) {
                this._score = databus.score;

                this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
                this.renderGameScore(this._ctx, this._score);
                this.updateTexture(this._texture);
            }
        }
    }

    renderGameScore(ctx, score) {
        ctx.textAlign = "left";
        ctx.fillStyle = '#ffffff'
        ctx.font = '20px Arial'

        ctx.fillText(score, 10, 10)
    }

    renderGameOver(ctx, score) {
        ctx.drawImage(atlas, 0, 0, 119, 107, screenWidth / 2 - 150, screenHeight / 2 - 100, 300, 300)

        ctx.fillStyle = '#ffffff'
        ctx.font = '20px Arial'
        ctx.textAlign = "center";

        ctx.fillText(
            '游戏结束',
            screenWidth / 2,
            screenHeight / 2 - 100 + 50
        )

        ctx.fillText(
            `得分: ${score}`,
            screenWidth / 2,
            screenHeight / 2 - 100 + 130
        )

        ctx.drawImage(
            atlas,
            120, 6, 39, 24,
            screenWidth / 2 - 60,
            screenHeight / 2 - 100 + 180,
            120, 40
        )

        ctx.fillText(
            '重新开始',
            screenWidth / 2,
            screenHeight / 2 - 100 + 190
        )

        this.btnArea = {
            startX: screenWidth / 2 - 60,
            startY: screenHeight / 2 - 100 + 180,
            endX: screenWidth / 2 + 60,
            endY: screenHeight / 2 - 100 + 220
        }
    }
}